package com.yupi;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.yupi.model.ExecuteCodeRequest;
import com.yupi.model.ExecuteCodeResponse;
import com.yupi.model.ExecutorMessage;
import com.yupi.model.JudgeInfo;
import com.yupi.security.DefaultSecurityManager;
import com.yupi.utils.ProcessUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * @Author FengHuan Wang
 * @Date 2025/3/10 9:04
 * @Version 1.0
 */
public class JavaNativeCodeSanBoxImpl implements CodeSanBox {

    /**
     * 代码存放路径名称
     */
    private static final String GLOBAL_CODE_DIR_NAME = "tmpCode";
    /**
     * Java程序文件名（主类名）
     */
    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";
    /**
     * 设置Java程序运行超时时间
     */
    private static final Long TIME_OUT = 5000L;

    /**
     * Java安全管理器路径
     */
    private static final String SECURITY_MANAGER_PATH = "E:\\JavaProject\\yuoj-sandbox\\src\\main\\java\\com\\yupi\\security";

    private static final String SECURITY_MANAGER_CLASSNAME = "MySecurityManager.class";

    /**
     * 代码敏感词集合
     */
    private static final List<String> blockLost = Arrays.asList("Files", "exec");

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        System.setSecurityManager(new DefaultSecurityManager());
        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();
        String language = executeCodeRequest.getLanguage();


        //把用户的代码保存为文件
        String userDir = System.getProperty("user.dir");
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        //判断全局代码目录是否存在？没有就新建文件
        if (!FileUtil.exist(globalCodePathName)){
            FileUtil.mkdir(globalCodePathName);
        }
        //把用户的代码隔离存放
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);

        //编译代码，得到class文件
        String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsolutePath());
        try {
            Process complieProcess = Runtime.getRuntime().exec(compileCmd);
            ExecutorMessage executorMessage = ProcessUtils.runProcess(complieProcess, "编译");
            System.out.println(executorMessage.toString());
        } catch (Exception e) {
            getErrorResponse(e);
            e.printStackTrace();
        }
        //执行代码,得到输出结果
        List<ExecutorMessage> executorMessageList = new ArrayList<>();
        for (String inputArgs : inputList) {
            String runCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s;%s -Djava.security.manager=%s Main %s", userCodeParentPath, SECURITY_MANAGER_PATH, SECURITY_MANAGER_CLASSNAME, inputArgs);
            try {
                Process runProcess = Runtime.getRuntime().exec(runCmd);
                // 超时控制
                new Thread(() -> {
                    try {
                        Thread.sleep(TIME_OUT);
                        System.out.println("超时了，中断");
                        runProcess.destroy();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }).start();
                ExecutorMessage executeMessage = ProcessUtils.runProcess(runProcess, "运行");
//                ExecuteMessage executeMessage = ProcessUtils.runInteractProcessAndGetMessage(runProcess, inputArgs);
                System.out.println(executeMessage);
                executorMessageList.add(executeMessage);
            } catch (Exception e) {
                return getErrorResponse(e);
            }
        }
        //收集整理输出结果
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        Long maxTime = 0L;
        List<String> outputList = new ArrayList<>();
        for (ExecutorMessage executorMessage : executorMessageList) {
            String errorMessage = executorMessage.getErrorMessage();
            if (StrUtil.isNotBlank(errorMessage)){
                //执行程序中存在错误
                executeCodeResponse.setMessage(errorMessage);
                executeCodeResponse.setStatus(3);
                break;
            }
            outputList.add(executorMessage.getMessage());
            Long time = executorMessage.getTime();
            if (time != null){
                maxTime = Math.max(maxTime, time);
            }
        }
        //正常运行完成
        if (outputList.size() == executorMessageList.size()){
            executeCodeResponse.setStatus(1);
        }
        executeCodeResponse.setOutputList(outputList);
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTimeLimit(maxTime);
        //文件清理
        if (userCodeFile.getParentFile() != null){
            boolean del = FileUtil.del(userCodeParentPath);
            System.out.println("删除" + (del ? "成功" : "失败"));
        }
        return executeCodeResponse;
    }


    /**
     * 获取错误响应
     * @param e
     * @return
     */
    private ExecuteCodeResponse getErrorResponse(Throwable e){
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());
        //表示代码沙箱错误
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return  executeCodeResponse;
    }
}
